package utils.paramUtil;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Map;
import java.util.Objects;

/**
 * @program: mall-order
 * @description: 参数工具类
 * @author: sam
 * @create: 2018-09-18 08:52
 * @update: 2018-09-18 08:52
 * @update: Sam
 **/
public class ParamUtils {

	public static Double formatNullToZero(Double d) {
		if (Objects.isNull(d)) {
			return 0.0;
		} else {
			return d;
		}
	}

	// 校验参数是否非空
	public static boolean checkParamsNonNull(Object... objs) {
		for (Object obj : objs) {
			if (Objects.isNull(obj)) {
				return false;
			}
			if (obj instanceof String) {
				if (StringUtils.isBlank((String) obj)) {
					return false;
				}
			}
			if (obj instanceof Collection) {
				if (CollectionUtils.isEmpty((Collection) obj)) {
					return false;
				}
			}
			if (obj instanceof Map) {
				if (MapUtils.isEmpty((Map) obj)) {
					return false;
				}
			}
		}
		return true;
	}

	public static boolean checkParamsIsNull(Object... objs) {
		return !checkParamsNonNull(objs);
	}


	// 通过 获取对象的每一个属性值 来判断对象是否为空
	public static boolean assertObjectIsEmpty(Object obj) {
		Field[] fields = obj.getClass().getDeclaredFields(); //获取实体类的所有属性，返回Field数组
		for (Field field : fields) {
			IgnoreFiled ignoreFiled = field.getDeclaredAnnotation(IgnoreFiled.class);
			if (Objects.nonNull(ignoreFiled)) {
				continue;
			}
			String fieldName = field.getName();
			String firstLetter = fieldName.substring(0, 1).toUpperCase();
			String getter = "get" + firstLetter + fieldName.substring(1);
			try {
				Method method = obj.getClass().getMethod(getter);
				Object value = method.invoke(obj);
				if (Objects.isNull(value) || StringUtils.isBlank(String.format("%s", value)) || "null".equals(String.format("%s", value))) {
					continue;
				} else {
					return false;
				}
			} catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
				e.printStackTrace();
			}
		}
		return true;
	}
}
